package com.jsb.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.annotation.SystemControllerLog;
import com.jsb.service.AnswerService;
import com.jsb.service.CategoryService;
import com.jsb.service.CompanyService;
import com.jsb.service.CounselorService;
import com.jsb.service.DutyService;
import com.jsb.service.LevelService;
import com.jsb.service.QuestionService;
import com.jsb.service.QuestionUserService;
import com.jsb.service.UserService;
import com.jsb.common.config.Const;
import com.jsb.common.utils.StringUtils;
import com.jsb.dto.UserCompany;
import com.jsb.dto.UserCounselorCompany;
import com.jsb.model.AnswerExample;
import com.jsb.model.Category;
import com.jsb.model.Company;
import com.jsb.model.Counselor;
import com.jsb.model.CounselorExample;
import com.jsb.model.Duty;
import com.jsb.model.Level;
import com.jsb.model.LevelExample;
import com.jsb.model.QuestionExample;
import com.jsb.model.QuestionUserExample;
import com.jsb.model.CounselorExample.Criteria;
import com.jsb.model.User;

@Controller
public class CounselorController{
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/counselor/list.do";
	
	@Resource
	private CounselorService counselorService;
	
	@Resource
	private CompanyService companyService;
	
	@Resource
	private UserService userService;
	
	@Resource LevelService levelService;
	
	@Resource
	private QuestionService questionService;
	@Resource
	private QuestionUserService questionUserService;
	@Resource
	private AnswerService answerService;
	
	@Resource
	private DutyService dutyService;
	@Resource
	private CategoryService categoryService;
	
	@RequestMapping("/counselor/list")
	public String list(
			Model model,String userPhoneNumber,String status,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		CounselorExample counselorExample = new CounselorExample();
		if(StringUtils.isEmpty(userPhoneNumber)){
			Criteria createCriteria = counselorExample.createCriteria();
			if(StringUtils.isNotEmpty(status)){
				createCriteria.andStatusEqualTo(Integer.valueOf(status));
			}
		}else{
			List<User> userByLikePhone = userService.getUserByLikePhone(userPhoneNumber);
			for (User user : userByLikePhone) {
				String userid = user.getPhoneNumber();
				Criteria createCriteria = counselorExample.createCriteria();
				if(StringUtils.isNotEmpty(userid)){
					createCriteria.andUserPhoneNumberLike("%"+userid+"%");
				}
				if(StringUtils.isNotEmpty(status)){
					createCriteria.andStatusEqualTo(Integer.valueOf(status));
				}
				counselorExample.or(createCriteria);
			}
		}
		
		int totalCount = counselorService.countCounselor(counselorExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		counselorExample.setPageIndex((pageNum - 1) * pageSize);
		counselorExample.setPageSize(pageSize);
		counselorExample.setOrderByClause("applyDate DESC");
		List<Counselor> counselors = counselorService.getPageCounselor(counselorExample);
		List<UserCounselorCompany> UserCounselorCompanys = new ArrayList<UserCounselorCompany>();
		for (Counselor counselor : counselors) {
			UserCounselorCompany userCounselorCompany = new UserCounselorCompany();
			User userByPhoneNumber = userService.getUserByPhoneNumber(counselor.getUserPhoneNumber());
			if(null != userByPhoneNumber && StringUtils.isNotEmpty(userByPhoneNumber.getCompanyUuid())){
				Company companyByUuid = companyService.getCompanyByUuid(userByPhoneNumber.getCompanyUuid());
				userCounselorCompany.setCompany(companyByUuid);
			}
			List<Duty> duties = new ArrayList<Duty>();  //职责
			if(null != userByPhoneNumber && StringUtils.isNotEmpty(userByPhoneNumber.getCounselorDuty())){
				String counselorDuty = userByPhoneNumber.getCounselorDuty();
				String[] str = counselorDuty.split(",");
				for (String s : str) {
					Duty dutyById = dutyService.getDutyById(s);
					duties.add(dutyById);
				}
			}
			
			if(StringUtils.isNotEmpty(counselor.getCounselorLevel())){
				Level level = levelService.getLevelByUuid(counselor.getCounselorLevel());
				userCounselorCompany.setLevel(level);
			}
			userCounselorCompany.setCounselor(counselor);
			userCounselorCompany.setUser(userByPhoneNumber);
			userCounselorCompany.setDuties(duties);
			UserCounselorCompanys.add(userCounselorCompany);
			
			//补充悬赏，抢答，偷看列
			String phoneNumber = counselor.getUserPhoneNumber();
			//从问题表中查询悬赏次数
			QuestionExample questionExample= new QuestionExample();
			questionExample.createCriteria().andPhoneNumEqualTo(phoneNumber);
			int questionCount = questionService.countQuestion(questionExample);
			userCounselorCompany.setQuestionCount(questionCount);
			//从回答表中查询抢答次数
			AnswerExample answerExample= new AnswerExample();
			answerExample.createCriteria().andPhoneNumberEqualTo(phoneNumber);
			int answerCount = answerService.countAnswer(answerExample);
			userCounselorCompany.setAnswerCount(answerCount);
			//从questionuser表中查询偷看次数
			QuestionUserExample questionUserExample = new QuestionUserExample();
			questionUserExample.createCriteria().andPhoneNumberEqualTo(phoneNumber);
			int questionUserCount = questionUserService.countQuestionUser(questionUserExample);
			userCounselorCompany.setQuestionUserCount(questionUserCount);
			
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("userPhoneNumber", userPhoneNumber);
		model.addAttribute("status", status);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("UserCounselorCompanys", UserCounselorCompanys);
		return "/Counselor/list";
	}
	
	@RequestMapping("/counselor/pass")
	@SystemControllerLog(description = "咨询师审核通过")
	public String pass(Model model,String duty,
            @RequestParam(value = "uuid", required = true) String uuid,String id){
	    String res = counselorService.updatePass(uuid,id,duty);
	    model.addAttribute("json", res);
	    return "/json";
	}

	@RequestMapping("/counselor/nopass")
	@SystemControllerLog(description = "咨询师审核不通过")
	public String nopass(Model model,
			@RequestParam(value = "uuid", required = true) String uuid,
			String aduitReason) {
		String info = "";
		Counselor counselorByUuid = counselorService.getCounselorByUuid(uuid);
		if (null != counselorByUuid) {
				Counselor counselor = new Counselor();
				counselor.setAduitReason(aduitReason);
				counselor.setStatus(Integer.valueOf(Const.CHECK_NOPASS));
				counselor.setUuid(uuid);
				
				String userPhoneNumber = counselorByUuid.getUserPhoneNumber();
				User user = new User();
				user.setPhoneNumber(userPhoneNumber);
				user.setRole(1);
				try {
					counselorService.updateNoPass(counselor,user);
					model.addAttribute("json",
							"{\"status\":\"y\",\"info\":\"审核成功\"}");
				} catch (Exception e) {
					e.printStackTrace();
				}
		} else {
			info = "未查询到该用户";
			model.addAttribute("json", "{\"status\":\"n\",\"info\":\"" + info
					+ "\"}");
		}
		return "/json";
	}
	
	@RequestMapping("/counselor/toAdd")
	public String toAdd(Model model) {
		return "/Counselor/add";
	}

	@RequestMapping("/counselor/add")
	public String add(Model model, @ModelAttribute("counselor") Counselor counselor) {
		counselorService.addCounselor(counselor);
		return redirect;
	}

	@RequestMapping("/counselor/del")
	public String del(Model model,
			@RequestParam(value = "uuid", required = true) String uuid) {
		counselorService.delCounselorByUuid(uuid);
		return redirect;
	}

	@RequestMapping("/counselor/toEdit")
	public String toEdit(Model model,
			@RequestParam(value = "uuid", required = true) String uuid) {
		Counselor counselor = counselorService.getCounselorByUuid(uuid);
		model.addAttribute("counselor", counselor);
		return "/Counselor/edit";
	}

	@RequestMapping("/counselor/edit")
	public String edit(Model model, @ModelAttribute("counselor") Counselor counselor) {
		counselorService.updateCounselor(counselor);
		return redirect;
	}

	@RequestMapping("/counselor/view")
	public String view(Model model,
			@RequestParam(value = "uuid", required = true) String uuid) {
		Counselor counselor = counselorService.getCounselorByUuid(uuid);
		User userByPhoneNumber = userService.getUserByPhoneNumber(counselor.getUserPhoneNumber());
		Company companyByUuid = companyService.getCompanyByUuid(userByPhoneNumber.getCompanyUuid());
		UserCounselorCompany userCounselorCompany = new UserCounselorCompany();
		//查询当前咨询师等级
		if(StringUtils.isNotEmpty(counselor.getCounselorLevel())){
			Level level = levelService.getLevelByUuid(counselor.getCounselorLevel());
			userCounselorCompany.setLevel(level);
			
		}
		//擅长业务
		String adept = counselor.getAdept();
		String adepts = "";
		if(StringUtils.isNotEmpty(adept)){
			if(adept.contains(adept)){
				String[] split = adept.split(",");
				for (String str : split) {
					Category categoryByUuid = categoryService.getCategoryByUuid(str);
					String name = categoryByUuid.getName();
					name+= ",";
					adepts += name;
				}
			}else{
				Category categoryByUuid = categoryService.getCategoryByUuid(adept);
				String name = categoryByUuid.getName();
				adepts = name;
			}
		}
		counselor.setAdept(adepts);
		userCounselorCompany.setCompany(companyByUuid);
		userCounselorCompany.setCounselor(counselor);
		userCounselorCompany.setUser(userByPhoneNumber);
		model.addAttribute("userCounselorCompany", userCounselorCompany);
		//查询所有等级
		LevelExample example = new LevelExample();
		example.setOrderByClause("money");
		List<Level> levels = levelService.selectByExample(example);
		model.addAttribute("levels", levels);
		//查询所有职责
		List<Duty> duties = dutyService.selectByExample(null);
		model.addAttribute("duties", duties);
		return "/Counselor/view";
	}
}
